package com.powernode.config.handler;

import com.powernode.constant.AuthConstants;
import com.powernode.model.R;
import com.powernode.util.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 登出成功处理器
 *  1.将redis中的令牌TOKEN删除
 *  authentication该认证对象已经由Security框架自行清空
 *  退出登录说明用户是已经登录的状态，所以用户的信息需要从约定好的位置获取，即请求头中
 *  前后端已约定好请求中令牌TOKEN存放的位置，请求头中的Authorization Beaer jwt
 */
@Component
public class AppLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 从请求头中获取令牌token
        String authorizationValue = request.getHeader(AuthConstants.AUTHORIZATION);
        String jwt_token = authorizationValue.replaceFirst(AuthConstants.BEARER, "");
        // 将token从redis中删除
        stringRedisTemplate.delete(AuthConstants.TOKEN_REDIS_KEY_PREFIX+jwt_token);
        // 响应结果
        ResponseUtils.write(response, R.OK("登出成功"));
    }
}
